package com.demo.camunda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.camunda.dao.UserDao;
import com.demo.camunda.entity.JwtUser;
import com.demo.camunda.entity.User;
import com.demo.camunda.service.UserService;
import com.demo.camunda.util.ExecptionExecution.ExceptionMapValue;
import com.demo.camunda.util.ExecptionExecution.ServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService, UserDetailsService {
    @Resource
    private UserDao userDao;

    @Override
    public User findUserById(String id) {
        User user = userDao.selectById(id);
        return user;
    }

    @Override
    public User addUser(User user) {
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<User>().eq(User::getUserName,user.getUserName());
        User ur = userDao.selectOne(lambdaQueryWrapper);
        if (ur != null) {
            throw  new ServiceException(ExceptionMapValue.getExceptionValue("USER_IS_EXISTED"));
        }
        userDao.insert(user);
        return user;
    }

    @Override
    public List<User> findAllUser() {
        List<User> users = userDao.selectList(new LambdaQueryWrapper<User>());
        return users;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<User>().eq(User::getUserName,username);
        User user = userDao.selectOne(lambdaQueryWrapper);
        if (user == null) {
            throw  new ServiceException(ExceptionMapValue.getExceptionValue("USER_NOT_FOUND"));
        }
        JwtUser jwtUser = new JwtUser(user);
        return jwtUser;
    }
}
